<?php

namespace App\Helpers\Lib;

use App\Exceptions\BusinessException;
use App\Exceptions\DaoException;
use App\Helpers\ResponseEnum;
use GuzzleHttp\Client;

class FuyouPay
{
    //测试的支付请求地址
    public static $base_uri = "https://aipaytest.fuioupay.com/";

    /**
     * 支付配置参数
     * @var array
     */
    static $config = [
        'mchnt_cd'=>'0002900F1503036',//商户号
        'mchnt_key'=>'f00dac5077ea11e754e14c9541bc0170',//支付的密钥
        'notice_url'=>'http://www.baidu.com',//支付的回调地址
        'version'=>'1.0',//支付使用的版本号
        'term_id'=>'123cqckj', //终端号（随机 8 字节数字字母组合）
        'term_ip'=>'127.0.0.1',//终端IP
        'sub_appid'=>'wxfa089da95020ba1a',//
    ];

    /**
     * 统一下单接口
     * @param $money
     * @param $order_no
     * @return void
     */
    public static function createPay($money=1,$order_no){
        $pay_arr = [
            'random_str'=>self::getRandom32Str(),//随机的32位支付字符串
            'order_amt'=>$money,//订单支付的总金额（以分为单位）
            'mchnt_order_no'=>$order_no,//支付的订单号(需要是30位的)
            'txn_begin_ts'=>date("YmdHms"),//交易的起始时间（yyyyMMddHHmmss）
            'goods_des'=>'buy goods',//商品的描述信息
            'term_id'=>self::$config['term_id'],//终端号
            'term_ip'=>self::$config['term_ip'],//终端IP
            'order_type'=>'WECHAT',//订单交易类型 （微信小程序支付）
            'mchnt_cd'=>self::$config['mchnt_cd'],//商户号
            'notify_url'=>empty($notice_url)?self::$config['notice_url']:$notice_url,
            'mchnt_key'=>self::$config['mchnt_key'],
            'sub_appid'=>self::$config['sub_appid'],
            'version'=>self::$config['version'],
            'trade_type'=>'LETPAY'
        ];

        $params = self::getBuildParams($pay_arr,['mchnt_cd','order_type','order_amt','mchnt_order_no','txn_begin_ts','goods_des','term_id','term_ip','notify_url','random_str','version','mchnt_key']);
        $client = new Client([
            // Base URI is used with relative requests
            'base_uri' => self::$base_uri,
            // You can set any number of default request options.
            'timeout'  => 2.0,
        ]);
        $res = $client->post('/aggregatePay/preCreate',[
            'json'=>$params,
        ]);
        $resArr = json_decode($res->getBody(),true);
        if($resArr['result_code']!=='000000'){
            throw new BusinessException(ResponseEnum::CLIENT_PARAMETER_ERROR,$resArr['result_msg']);
        }
        return $resArr;
    }


    /**
     * 小程序支付
     * @return void
     */
    public static function miniPay($openid = '',$money = 1,$order_no,$notice_url = ''){
        $pay_arr = [
            'random_str'=>self::getRandom32Str(),//随机的32位支付字符串
            'order_amt'=>$money,//订单支付的总金额（以分为单位）
            'mchnt_order_no'=>$order_no,//支付的订单号(需要是30位的)
            'txn_begin_ts'=>date("YmdHms"),//交易的起始时间（yyyyMMddHHmmss）
            'goods_des'=>'buy goods',//商品的描述信息
            'term_id'=>self::$config['term_id'],//终端号
            'term_ip'=>self::$config['term_ip'],//终端IP
            'trade_type'=>'LETPAY',//订单交易类型 （微信小程序支付）
            'openid'=>$openid,//用户的openid
            'mchnt_cd'=>self::$config['mchnt_cd'],//商户号
            'notify_url'=>empty($notice_url)?self::$config['notice_url']:$notice_url,
            'mchnt_key'=>self::$config['mchnt_key'],
            'sub_appid'=>self::$config['sub_appid'],
            'version'=>self::$config['version'],
        ];

        $params = self::getBuildParams($pay_arr,['mchnt_cd','trade_type','order_amt','mchnt_order_no','txn_begin_ts','goods_des','term_id','term_ip','notify_url','random_str','version','mchnt_key']);
        $client = new Client([
            // Base URI is used with relative requests
            'base_uri' => self::$base_uri,
            // You can set any number of default request options.
            'timeout'  => 2.0,
        ]);
        $res = $client->post('/aggregatePay/wxPreCreate',[
            'json'=>$params,
        ]);
        $resArr = json_decode($res->getBody(),true);
        if($resArr['result_code']!=='000000'){
            throw new BusinessException(ResponseEnum::CLIENT_PARAMETER_ERROR,$resArr['result_msg']);
        }
        return json_decode($resArr['reserved_pay_info'],true);
    }

    /**
     * 订单查询
     * @return void
     * $order_type
     * 订单类型：
     * ALIPAY(统一下单、条码支付、服务窗支付)
     * WECHAT(统一下单、条码支付，公众号支付)
     * UNIONPAY
     * WXAPP(微信app)
     * ALIAPP(支付宝app)
     * WXH5(微信h5)
     * ALIH5(支付宝h5)
     * WXBX(微信保险类)
     * ALBX(支付宝保险类)
     * WXXS(微信线上所有交易)
     * BESTPAY(翼支付)
     */
    public static function orderQuery($order_no,$order_type){
        $pay_arr = [
            'version'=>self::$config['version'],
            'mchnt_cd'=>self::$config['mchnt_cd'],//商户号
            'random_str'=>self::getRandom32Str(),//随机的32位支付字符串
            'order_type'=>$order_type,
            'mchnt_order_no'=>$order_no,
            'term_id'=>self::$config['term_id'],//终端号
            'term_ip'=>self::$config['term_ip'],//终端IP

        ];

        $params = self::getBuildParams($pay_arr,['mchnt_cd','trade_type','mchnt_order_no','term_id','random_str','version','mchnt_key']);
        $client = new Client([
            // Base URI is used with relative requests
            'base_uri' => self::$base_uri,
            // You can set any number of default request options.
            'timeout'  => 2.0,
        ]);
        $res = $client->post('/aggregatePay/wxPreCreate',[
            'json'=>$params,
        ]);
        var_dump($res);
    }

    /**
     * 订单的退款
     * @return void
     */
    public static function orderRefund(){

    }




    /**
     * 获取服务商的openid
     * @return \Psr\Http\Message\StreamInterface
     */
    public static function serviceOPenId(){
        $pay_arr = [
            'mchnt_cd'=>self::$config['mchnt_cd'],//商户号
            'redirect_uri'=>urlencode('https://dztxsother.19w.top/api/getserviceopenid?a=123')//重定向的地址
        ];
        $params = self::getBuildParams($pay_arr,['mchnt_cd','redirect_uri']);
        //echo http_build_query($params);
        header('Location:'.self::$base_uri.'aggregatePay/auth2Openid?'.http_build_query($params));
        //var_dump($res->getBody());
//        $resArr = json_decode($res->getBody(),true);
//        var_dump($resArr);
    }

    /**
     * 随机生成32位字符串
     * @return string
     */
    public static function getRandom32Str()
    {
        return md5( time() . mt_rand(0, 99999999) );
    }

    /**
     * @param array $data
     * @return string
     */
    public static function arraySplicingStr(array $data){
        $str = '';
        if(!empty($data)){
            foreach($data as $v){

                $str.= rtrim($v.'|');
            }
        }
        //如果参数中没有必填这个参数就把他拼在最后面
        if(!checkIsHasField($data,'mchnt_key')){
            $str.=self::$config['mchnt_key'];
        }
        return trim($str,'|');
    }



    private static function getBuildParams(array $req_arr,array $set_sign=[]){
        if(empty($req_arr)){
            return [];
        }
        $temp_set_sign = $set_sign;
        $set_sign = array_flip($set_sign);
        //获取数组的交集
        $last_arr = array_intersect_key($req_arr,$set_sign);
        if(empty($last_arr)){
            $last_arr = $req_arr;
        }
        $newData = array_replace(array_flip($temp_set_sign), $last_arr);
        //var_dump($newData);
//        foreach($set_sign as $k=>$v){
//            //$newData[$v] = $last_arr[$v];
//            var_dump($v);
//        }
        $str = self::arraySplicingStr($newData); //第一步
        //合并上面的字符串再次进行加密
        $sign = md5($str);
        $req_arr['sign'] = $sign;
        //var_dump($req_arr);
        return $req_arr;
        //接口请求的公共参数
//        $common_req = [
//            'app_id'=>self::$appId,
//            'timestamp'=>$now_time,
//            'v'=>self::$v,
//            'msg_digest'=>$sign
//        ];

        //return array_merge($req_arr,$common_req);

    }






}
